import { DemoBlock } from '@/components/demos-util';
import { type DetailResult } from '@/pages/types/type';
import { ACCESSTOKEN, emptyToken, setWithExpiry } from '@/utils/authorize';
import { getRequestInit, urlPrefix } from '@/utils/http';
import { Content, Page } from '@alita/flow';
import { Link, request } from 'alita';
import {
  Button,
  Divider,
  Form,
  Input,
  Radio,
  Result,
  Space,
} from 'antd-mobile';
import { useEffect, useState } from 'react';
// http://localhost:4085/#/temporary/clean-token

export default () => {
  interface User {
    value: string;
    label: string;
  }
  const token: string | null = localStorage.getItem(ACCESSTOKEN);
  const ok = token !== null && token.length > 10;
  const [ing, setIng] = useState<boolean>(false);
  const [fail, setFail] = useState<string | undefined>(undefined);
  const [success, setSuccess] = useState<string | undefined>(undefined);

  const [loading, setLoading] = useState<boolean>(true);
  const [loadFail, setLoadFail] = useState<string | undefined>(undefined);
  const [loadSuccess, setLoadSuccess] = useState<string | undefined>(undefined);
  const [users, setUsers] = useState<User[]>([]);

  function load() {
    setLoading(true);
    setLoadFail(undefined);
    setLoadSuccess(undefined);
    let response: Promise<Response> = fetch(
      `${urlPrefix}/api/rayplatform/wei-xin-user/get-all-for-confidential-44874-8841-8874`,
      getRequestInit(),
    );
    response
      .then((rsp: Response) => {
        console.log(rsp);
        if (rsp.ok) {
          rsp
            .json()
            .then(({ data, code, msg }: DetailResult<User[]>) => {
              if (code === 0) {
                setUsers(data!);
                setLoadSuccess(msg);
              } else {
                setLoadFail(msg);
              }
            })
            .catch((reason) => {
              setLoadFail(reason);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFail(`发生错误：${reason}`);
      })
      .finally(() => {
        setLoading(false);
      });
  }

  useEffect(load, []);

  useEffect(() => emptyToken(), []);

  const onFinish = (values: { userid: string }) => {
    /*Dialog.alert({
            content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        })*/
    setIng(true);
    request(`/api/rayplatform/wei-xin-user/get-token-test-1145-8748-88741-7452/${values.userid}`, {}).then(
      ({
        accessToken,
        tokenType,
      }: {
        accessToken: string;
        tokenType: string;
      }) => {
        setWithExpiry(ACCESSTOKEN, accessToken, 30 * 24 * 60 * 60 * 1000);
        setSuccess(`${tokenType}-ok`);
        setIng(false);
      },
    );
  };

  const extractWeiXinUserFromPermanent = (values: { permanentCode: string;}) => {
    setIng(true);
    request(
      `/api/qywx-sass-custom-app-tpl-create/extract-weiXin-user-from-permanent/${values.permanentCode}`,
      {},
    ).then(
      ({ data, code, msg }: { data: string; code: number; msg: string }) => {
        alert(`data=${data}, code=${code},msg=${msg}`);
        setIng(false);
      },
    );
  };

  const setWorkbenchTemplate =()=>{
    setIng(true);
    request(
      `/api/corp-agent-workbench-template/set-key-date-template`,
      {},
    ).then(
      ({ data, code, msg }: { data: string; code: number; msg: string }) => {
        alert(`data=${data}, code=${code},msg=${msg}`);
        setIng(false);
      },
    );
  }

  return (
    <Page>
      <Content>
        {ok && (
          <><DemoBlock title="本地登录" padding={6}>
            <h6>token={localStorage.getItem(ACCESSTOKEN)}</h6>
            <Button
              block
              size={'middle'}
              type={'button'}
              color="primary"
              shape={'rectangular'}
              onClick={() => emptyToken()}
            >
              清理
            </Button>
            <Divider />
            <Link to={'/opportunity/create'}>创建商机</Link>
            <Divider direction={'vertical'} />
            <Link to={'/customer/create'}>创建客户</Link>
            <Divider direction={'vertical'} />
            <Link to={'/block/create'}>项目立项</Link>
            <Divider direction={'vertical'} />
            <Link to={'/'}>首页</Link>
            <Divider direction={'vertical'} />
           
            
          </DemoBlock>
          <DemoBlock title="初始化" padding={6}>
            <Space direction={'vertical'}>
                <Link to={'/backend/oa-system/apply'}>OA初始化</Link>
                <Button type={'button'} color={'primary'} fill={'none'} onClick={setWorkbenchTemplate} >设置工作台为模板</Button>
            </Space>
          </DemoBlock>
          </>

        )}
        {!ok && (
          <>
            <DemoBlock title="" padding={6}>
              <Result
                status="warning"
                title="警告提示"
                description={
                  <>
                    你在本地没有登录凭据。 <Divider direction="vertical" />
                    <Link to={`/`}>首页</Link>
                  </>
                }
              />
              <Form
                layout={'vertical'}
                onFinish={onFinish}
                footer={
                  <>
                    <Button
                      block
                      type="submit"
                      disabled={
                        ing || fail !== undefined || success !== undefined
                      }
                      loading={ing}
                      color="primary"
                      size="large"
                    >
                      {success !== undefined ? '已创建' : '创建凭据'}
                    </Button>
                  </>
                }
              >
                <Form.Header>登录</Form.Header>
                <Form.Item
                  name="userid"
                  label="选择用户"
                  rules={[{ required: true, message: '选择用户' }]}
                >
                  <Radio.Group>
                    <Space direction="vertical">
                      {users.map(({ value, label }) => (
                        <Radio key={value} value={value}>
                          {label}
                          <span style={{ fontSize: '10px' }}> ({value})</span>
                        </Radio>
                      ))}
                    </Space>
                  </Radio.Group>
                </Form.Item>
              </Form>

              <Form
                layout={'vertical'}
                onFinish={extractWeiXinUserFromPermanent}
                footer={
                  <>
                    <Button
                      block
                      type="submit"
                      disabled={ing}
                      loading={ing}
                      color="primary"
                      size="large"
                    >
                      {success !== undefined
                        ? '创建第一个用户'
                        : '创建第一个用户'}
                    </Button>
                  </>
                }
              >
                <Form.Header>创建第一个用户</Form.Header>
                <Form.Item
                  name="permanentCode"
                  label="授权码"
                  rules={[{ required: true, message: '授权码' }]}
                >
                  <Input placeholder="请查询数据库输入授权码" clearable />
                </Form.Item>
              </Form>
            </DemoBlock>
          </>
        )}
      </Content>
    </Page>
  );
};
